package com.jz.community.moduleshopping.address.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;

import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.jz.community.basecomm.bean.BaseCommLocateInfo;
import com.jz.community.basecomm.bean.LocationInfo;
import com.jz.community.basecomm.utils.BaseSpUtils;
import com.jz.community.basecomm.utils.CommUtils;
import com.jz.community.basecomm.utils.ConverterUtils;
import com.jz.community.basecomm.utils.LoggerUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.SHelper;
import com.jz.community.moduleshopping.R;
import com.jz.community.moduleshopping.address.adapter.SearchAddressAdapter;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * Created by Tony.Fan on 2018/6/7 10:42
 */
public class SearchAddressControl implements PoiSearch.OnPoiSearchListener, Inputtips.InputtipsListener {
    private Activity mContext;
    private RecyclerView searchNearAddressRecyclerView;
    private EditText etBelongAddressDetail;
    private SearchAddressAdapter searchAddressAdapter;
    private String cityCode;

    public SearchAddressControl(Activity context) {
        mContext = context;
    }

    public void showUI() {
        searchNearAddressRecyclerView = mContext.findViewById(R.id.search_near_address_recyclerView);
        etBelongAddressDetail = mContext.findViewById(R.id.et_belong_address_detail);
        searchEditTextListener();
    }

    /**
     * 城市code
     *
     * @param cityCode
     */
    public void setCityCode(String cityCode) {
        this.cityCode = cityCode;
    }

    @SuppressLint("CheckResult")
    private void searchEditTextListener() {
        RxTextView.textChangeEvents(etBelongAddressDetail)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(onTextChangeEvent -> {
                    if (!Preconditions.isNullOrEmpty(onTextChangeEvent.text().toString()) && !Preconditions.isNullOrEmpty(cityCode)) {
                        InputtipsQuery inputQuery = new InputtipsQuery(onTextChangeEvent.text().toString(), cityCode);
                        Inputtips inputTips = new Inputtips(mContext, inputQuery);
                        inputTips.setInputtipsListener(this);
                        inputTips.requestInputtipsAsyn();
                    } else {
                        SHelper.gone(searchNearAddressRecyclerView);
                    }
                });
    }

    /**
     * 绑定地址列表
     *
     * @param locationInfos
     */
    private void handleSearchAddressAdapter(List<LocationInfo> locationInfos) {
        LinearLayoutManager goods_layoutManager = new LinearLayoutManager(mContext);
        searchNearAddressRecyclerView.setLayoutManager(goods_layoutManager);
        searchAddressAdapter = new SearchAddressAdapter(locationInfos);
        searchNearAddressRecyclerView.setAdapter(searchAddressAdapter);
        searchAddressAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                String address = searchAddressAdapter.getData().get(position).getTitle() + searchAddressAdapter.getData().get(position).getAddress();
                etBelongAddressDetail.setText(address);
                etBelongAddressDetail.setSelection(address.length());
                saveLocationMsg(ConverterUtils.toString(searchAddressAdapter.getData().get(position).getLongitude()), ConverterUtils.toString(searchAddressAdapter.getData().get(position).getLatitude()), searchAddressAdapter.getData().get(position).getAreaCode());
                CommUtils.hideKeyboard(view, mContext);
                SHelper.gone(searchNearAddressRecyclerView);
                cityCode = "";
            }
        });
    }

    /**
     * 保存定位经纬度信息
     *
     * @param longitude
     * @param latitude
     */
    private void saveLocationMsg(String longitude, String latitude, String areaCode) {
        BaseCommLocateInfo locateInfo = new BaseCommLocateInfo();
        locateInfo.lon = longitude;
        locateInfo.lat = latitude;
        locateInfo.areaCode = areaCode;
        locateInfo.citycode = cityCode;
        BaseSpUtils.getInstance().setCurrentCommuity(mContext, locateInfo);
    }

    @Override
    public void onGetInputtips(List<Tip> tipList, int rCode) {
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {// 正确返回
            SHelper.vis(searchNearAddressRecyclerView);
            loadSearchAddressList(tipList);
        }
    }

    /**
     * 加载搜索列表
     *
     * @param tipList
     */
    private void loadSearchAddressList(List<Tip> tipList) {
        List<LocationInfo> locationInfos = new ArrayList<>();
        LoggerUtils.fLog().i("PoiResultList" + tipList.size());
        for (int i = 0; i < tipList.size(); i++) {
            Tip item = tipList.get(i);
            if (!Preconditions.isNullOrEmpty(item.getPoint())) {
                String areaCode = item.getAdcode();
                String address = item.getAddress();
                String name = item.getName();
                LocationInfo locationInfo = new LocationInfo();
                locationInfo.setAddress(address);
                locationInfo.setTitle(name);
                locationInfo.setAreaCode(areaCode);
                locationInfo.setLatitude(item.getPoint().getLatitude());
                locationInfo.setLongitude(item.getPoint().getLongitude());
                locationInfos.add(locationInfo);
            }
        }
        handleSearchAddressAdapter(locationInfos);
    }

    @Override
    public void onPoiSearched(PoiResult poiResult, int i) {

    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {
    }


}
